package com.daigoudao.web.action;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.daigoudao.config.ConfigManager;
import com.daigoudao.util.Constants;
import com.daigoudao.util.FileUtil;
import com.daigoudao.util.ImageUtil;
import com.daigoudao.web.common.BasePageAction;
import com.daigoudao.web.model.AreaModel;
import com.daigoudao.web.model.CanBuyModel;
import com.daigoudao.web.model.CategoryModel;
import com.daigoudao.web.model.EvaluateModel;
import com.daigoudao.web.model.PurchaseRecord;
import com.daigoudao.web.model.TopTagModel;
import com.daigoudao.web.model.TransInfoModel;
import com.daigoudao.web.model.UserModel;
import com.daigoudao.web.service.ICanBuyService;
import com.daigoudao.web.service.ICommonService;
import com.daigoudao.web.service.IEvaluateService;
import com.daigoudao.web.service.ITransInfoService;

/**
 * 代购action类
 * 
 * @author zheng
 * 
 */
@SuppressWarnings("serial")
public class CanBuyAction extends BasePageAction {

	private static Logger logger = LoggerFactory.getLogger(CanBuyAction.class);

	private ICanBuyService canBuyService;

	private ICommonService commonService;

	private ITransInfoService transInfoService;

	private IEvaluateService evaluateService;

	private EvaluateModel evaluateModel;

	private CanBuyModel canBuyModel;

	private TransInfoModel transInfoModel;

	/**
	 * 上传的文件
	 */
	private List<File> image;

	/**
	 * 上传的文件名称
	 */
	private List<String> imageFileName;

	private List<String> imageContentType;

	private List<CategoryModel> categorys;

	private List<TopTagModel> topTags;

	private List<AreaModel> areas;

	private List<CanBuyModel> canBuyModels;

	private List<PurchaseRecord> records;

	private List<CanBuyModel> otherCanBuys;

	private List<EvaluateModel> evaluateModels;

	/**
	 * 综合评价
	 */
	private float avgEvaluate;

	/**
	 * 初始化发布代购页面
	 * 
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public String initAddCanBuy() throws Exception {
		UserModel loginModel = getUserLogin();
		if (loginModel == null) {
			session.put(Constants.URL, "initAddCanBuy.htm");
			return LOGIN;
		}
		if (Constants.USER_TYPE_BROKER != loginModel.getUserType()) {
			session.put(Constants.URL, "initAddCanBuy.htm");
			return CERTIFICATION;
		}
		try {
			categorys = commonService.queryCategorys();
			areas = commonService.queryAreas();

		} catch (Exception e) {
			logger.error("initAddCanBuy error.", e);
			return ERROR;
		}
		return SUCCESS;
	}

	/**
	 * 初始化修改页面
	 * 
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public String initEdit() {
		UserModel userModel = getUserLogin();
		if (userModel == null) {
			session.put(Constants.URL, "initEditCanBuy.htm?id=" + id);
			return LOGIN;
		}

		if (Constants.USER_TYPE_BROKER != userModel.getUserType()) {
			session.put(Constants.URL, "initEditCanBuy.htm?id=" + id);
			return CERTIFICATION;
		}

		try {
			canBuyModel = canBuyService.queryCanBuyDetail(id);
			if (canBuyModel == null) {
				return ERROR;
			}
			categorys = commonService.queryCategorys();
			areas = commonService.queryAreas();
		} catch (Exception e) {
			logger.error("initEditCanBuy error.", e);
			return ERROR;
		}
		return SUCCESS;
	}

	/**
	 * 修改代购信息
	 * 
	 * @return
	 */
	public String edit() {
		List<String> images = uploadImages();
		canBuyModel.setImages(images);
		try {
			canBuyService.updateCanBuy(canBuyModel);
		} catch (Exception e) {
			logger.error("edit error.", e);
			return ERROR;
		}
		return SUCCESS;
	}

	/**
	 * 添加代购信息
	 * 
	 * @return
	 */
	public String addCanBuy() throws Exception {
		List<String> images = uploadImages();
		canBuyModel.setImages(images);
		try {
			canBuyService.addCanBuy(canBuyModel);
		} catch (Exception e) {
			logger.error("addCanBuy error.", e);
			return ERROR;
		}
		return SUCCESS;
	}

	/**
	 * 显示代购信息页
	 * 
	 * @return
	 */
	public String showCanBuys() {
		try {
			areas = commonService.queryAreas();
			categorys = commonService.queryCategorys();
			topTags = commonService.queryTags();
			categorys.add(0, new CategoryModel(0, "不限"));
			areas.add(0, new AreaModel(0, "不限"));
			topTags.add(0, new TopTagModel(0, "不限"));

			CanBuyModel query = new CanBuyModel();
			if (0 != id) {
				query.setCategoryId(id);
			}
			query.setGoodsName(getQ());
			query.setAreaId(getArea());
			query.setCategoryId(getCategory());
			query.setTagId(getTag());
			query.setStartIndex((getSuperPage() - 1) * getPageSize());
			query.setPageSize(getPageSize());
			query.setStatus(0);
			query.setIsOpen(0);
			if (getPubtime() != 0) {
				query.setTs(processPubtime());
			}
			if (isLogin()) {
				query.setNotEqualUserId(getUserLogin().getUserid());
			}
			canBuyModels = canBuyService.queryCanBuys(query);
			setTotalSize(canBuyService.getCanBuyCount(query));
		} catch (Exception e) {
			logger.error("initCanBuyList error.", e);
			return ERROR;
		}
		return SUCCESS;
	}

	/**
	 * 查询代购详情
	 * 
	 * @return
	 */
	public String queryCanBuyDetail() {
		if (0 != id) {
			canBuyModel = new CanBuyModel();
			canBuyModel.setCanId(id);
		}
		try {
			canBuyModel = canBuyService.queryCanBuyDetail(canBuyModel
					.getCanId());
			CanBuyModel queryModel = new CanBuyModel();
			queryModel.setPageSize(12);
			queryModel.getUser().setUserid(canBuyModel.getUser().getUserid());
			queryModel.setCanId(canBuyModel.getCanId());
			otherCanBuys = canBuyService.queryOtherCanBuys(queryModel);
		} catch (Exception e) {
			logger.error("queryCanBuyDetail error.", e);
			return ERROR;
		}
		return SUCCESS;
	}

	/**
	 * 根据分类查询代购信息
	 * 
	 * @return
	 */
	public String queryCanBuysByUser() {
		try {
			canBuyModel.getUser().setUserid(getUserLogin().getUserid());
			canBuyModel.setPageSize(0);
			canBuyModel.setStatus(0);
			canBuyModels = canBuyService.queryCanBuys(canBuyModel);
		} catch (Exception e) {
			logger.error("queryCanBuysByUser error.", e);
			return ERROR;
		}
		return SUCCESS;
	}

	/**
	 * 查询代购交易记录
	 * 
	 * @return
	 */
	public String queryPurchaseRecords() {
		try {
			PurchaseRecord record = new PurchaseRecord();
			record.setStartIndex((getSuperPage() - 1) * getPageSize());
			record.setProductId(id);
			records = transInfoService.queryPurchaseRecords(record);
			setTotalSize(transInfoService.getPurhcaseRecordCount(record));
		} catch (Exception e) {
			logger.error("queryPurchaseRecords error.", e);
			return ERROR;
		}
		return SUCCESS;
	}

	/**
	 * 查询评价信息
	 * 
	 * @return
	 */
	public String queryEvaluates() {
		try {
			evaluateModel.setStartIndex((getSuperPage() - 1) * getPageSize());
			evaluateModels = evaluateService.queryEvaluates(evaluateModel);
			setTotalSize(evaluateService.getEvaluateCount(evaluateModel));
			if (getTotalSize() > 0) {
				float avg = evaluateService.queryAvgEvaluateLevel(evaluateModel
						.getCanId());
				avgEvaluate = new BigDecimal(avg).setScale(2,
						BigDecimal.ROUND_HALF_UP).floatValue();
			}
		} catch (Exception e) {
			logger.error("queryEvaluates error.", e);
			return ERROR;
		}
		return SUCCESS;
	}

	public void setCommonService(ICommonService commonService) {
		this.commonService = commonService;
	}

	public void setCanBuyService(ICanBuyService canBuyService) {
		this.canBuyService = canBuyService;
	}

	public List<TopTagModel> getTopTags() {
		return topTags;
	}

	public void setTopTags(List<TopTagModel> topTags) {
		this.topTags = topTags;
	}

	public void setTransInfoService(ITransInfoService transInfoService) {
		this.transInfoService = transInfoService;
	}

	public void setRecords(List<PurchaseRecord> records) {
		this.records = records;
	}

	public List<PurchaseRecord> getRecords() {
		return records;
	}

	public TransInfoModel getTransInfoModel() {
		return transInfoModel;
	}

	public void setTransInfoModel(TransInfoModel transInfoModel) {
		this.transInfoModel = transInfoModel;
	}

	public List<CanBuyModel> getOtherCanBuys() {
		return otherCanBuys;
	}

	public void setOtherCanBuys(List<CanBuyModel> otherCanBuys) {
		this.otherCanBuys = otherCanBuys;
	}

	public List<EvaluateModel> getEvaluateModels() {
		return evaluateModels;
	}

	public void setEvaluateModels(List<EvaluateModel> evaluateModels) {
		this.evaluateModels = evaluateModels;
	}

	public float getAvgEvaluate() {
		return avgEvaluate;
	}

	public void setAvgEvaluate(float avgEvaluate) {
		this.avgEvaluate = avgEvaluate;
	}

	public EvaluateModel getEvaluateModel() {
		return evaluateModel;
	}

	public void setEvaluateModel(EvaluateModel evaluateModel) {
		this.evaluateModel = evaluateModel;
	}

	public CanBuyModel getCanBuyModel() {
		return canBuyModel;
	}

	public void setCanBuyModel(CanBuyModel canBuyModel) {
		this.canBuyModel = canBuyModel;
	}

	public List<CanBuyModel> getCanBuyModels() {
		return canBuyModels;
	}

	public void setCanBuyModels(List<CanBuyModel> canBuyModels) {
		this.canBuyModels = canBuyModels;
	}

	public List<CategoryModel> getCategorys() {
		return categorys;
	}

	public void setCategorys(List<CategoryModel> categorys) {
		this.categorys = categorys;
	}

	public List<AreaModel> getAreas() {
		return areas;
	}

	public void setAreas(List<AreaModel> areas) {
		this.areas = areas;
	}

	public void setEvaluateService(IEvaluateService evaluateService) {
		this.evaluateService = evaluateService;
	}

	public List<File> getImage() {
		return image;
	}

	public void setImage(List<File> image) {
		this.image = image;
	}

	public List<String> getImageFileName() {
		return imageFileName;
	}

	public void setImageFileName(List<String> imageFileName) {
		this.imageFileName = imageFileName;
	}

	public List<String> getImageContentType() {
		return imageContentType;
	}

	public void setImageContentType(List<String> imageContentType) {
		this.imageContentType = imageContentType;
	}

	private List<String> uploadImages() {
		List<String> images = new ArrayList<String>();
		if (image != null) {
			String root = ConfigManager.getConfigString("upload.resDir");
			String path = com.daigoudao.util.StringUtils.formatDate(new Date(),
					"yyyy-MM-dd");
			String basePath = root + File.separator + path;
			FileUtil.createDir(basePath);
			// 循环上传的文件
			for (int i = 0; i < image.size(); i++) {
				// 获取文件扩展名
				String fileName = imageFileName.get(i);
				String extName = FileUtil.getExtention(fileName);

				fileName = com.daigoudao.util.StringUtils.getUUID() + extName;
				File destFile = new File(basePath, fileName);

				// 文件复制
				try {
					FileUtil.copy(image.get(i), destFile);
				} catch (Exception e) {
				}

				// 处理文件
				try {
					boolean result = ImageUtil.resize300(destFile.getPath());
					result &= ImageUtil.resize50(destFile.getPath());
					result &= ImageUtil.resize200(destFile.getPath());
					if (result) {
						logger.error("上传的图片格式不符合要求");
					}
				} catch (IOException e) {
					logger.error("ImageUtil resize ERROR", e);
				}
				// 文件在数据库存储
				String urlPath = File.separator + path + File.separator
						+ fileName;
				// 保存到数据库
				images.add(urlPath);
			}
		}
		return images;
	}
}
